//
// Created by lanlu on 2025/8/7.
//

#include <vector>
#include <iostream>
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;

    TreeNode() : val(0), left(nullptr), right(nullptr)
    {
    }

    TreeNode(int x) : val(x), left(nullptr), right(nullptr)
    {
    }

    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right)
    {
    }
};

class Solution {
public:
    vector<int> preorderTraversal(TreeNode *root)
    {
        vector<int> result;
        preorder(root, result);
        return result;
    }

    // 构造递归函数 处理根节点和结果集  vector使用引用类型
    void preorder(TreeNode *root, vector<int> &result)
    {
        // 递归出口
        if (root == nullptr) return;
        // 递归规律
        result.push_back(root->val);
        preorder(root->left, result);
        preorder(root->right, result);
    }
};

int main()
{
    TreeNode *root = new TreeNode(1);
    root->right = new TreeNode(2);
    root->right->left = new TreeNode(3);

    vector<int> v = Solution().preorderTraversal(root);
    for (int i : v)
    {
        cout << i << " ";
    }
    cout << endl;
}
